package db

import (
	"fmt"
	"log"
	"os"
	"time"

	"naive-admin-go/utils"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var Dao *gorm.DB

func Init() {
	dbLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold:             time.Second,
			Colorful:                  false,
			IgnoreRecordNotFoundError: true,
			ParameterizedQueries:      false,
			LogLevel:                  logger.Info,
		},
	)

	confDir := utils.GetConfigDir()
	DBFile := fmt.Sprintf("%s/gocrud.db", confDir)
	openDb, err := gorm.Open(sqlite.Open(DBFile), &gorm.Config{
		Logger:                                   dbLogger,
		DisableForeignKeyConstraintWhenMigrating: true,
	})
	if err != nil {
		log.Fatalf("db connection error is %s", err.Error())
	}
	dbCon, err := openDb.DB()
	if err != nil {
		log.Fatalf("openDb.DB error is  %s", err.Error())
	}
	dbCon.SetMaxIdleConns(3)
	dbCon.SetMaxOpenConns(10)
	dbCon.SetConnMaxLifetime(time.Hour)

	// 读取SQL文件
	// pwd, _ := os.Getwd()
	// initsqlUrl := pwd + "/sqlite3.sql"
	// sqlFileContent, err := os.ReadFile(initsqlUrl)
	// if err != nil {
	// 	log.Fatalf("导入初始化init.sql失败 %s", err)
	// }
	// sqlFileContentStr := string(sqlFileContent)
	// log.Println(sqlFileContentStr)
	// // 将SQL文件内容导入到数据库
	// _, err = dbCon.Exec(sqlFileContentStr)
	// if err != nil {
	// 	log.Fatal(err)
	// }

	Dao = openDb
}
